package arcade;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
 * Controller
 * 
 * The controller provides a way to associate keys to behaviors.  When a key is
 * pressed it should trigger the controller to walk through each of the assigned
 * behaviors.  It is also possible to remove assigned behaviors based on the key
 * or the behavior.
 * 
 * @author Alexander Schearer <aas11@duke.edu>
 */
public class Controller {

	private HashMap<Character, List<Behavior>> myActions;

	public Controller() {
		myActions = new HashMap<Character, List<Behavior>>();
	}

	public boolean bindKey(Character key, Behavior b) {
		List<Behavior> actions = getBehaviorsFor(key);
		if (actions.contains(b))
			return false;
		actions.add(b);
		myActions.put(key, actions);
		return true;
	}

	public boolean freeKey(Character key, Behavior b) {
		List<Behavior> actions = getBehaviorsFor(key);
		if (actions.contains(b)) {
			actions.remove(b);
			myActions.put(key, actions);
			return true;
		}
		return false;
	}

	public boolean freeKey(Character key, String b) {
		List<Behavior> actions = getBehaviorsFor(key);
		for (int i = 0; i < actions.size(); i++) {
			if (actions.get(i).equals(b)) {
				actions.remove(i);
				myActions.put(key, actions);
				return true;
			}
		}
		return false;
	}

	public boolean freeKey(Character key) {
		List<Behavior> actions = getBehaviorsFor(key);
		actions.clear();
		myActions.put(key, actions);
		return true;
	}

	public void trigger(Character event) {
		List<Behavior> actions = getBehaviorsFor(event);
		for (Behavior b : actions) {
			b.step();
		}
	}

	private List<Behavior> getBehaviorsFor(Character event) {
		List<Behavior> list = myActions.get(event);
		if (list == null)
			list = new ArrayList<Behavior>();
		return list;
	}

}
